package org.jeecg.modules.fw.controller;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.service.IBusWaiterService;
import org.jeecg.modules.fw.dto.RoomCleanDto;
import org.jeecg.modules.fw.dto.RoomLockDto;
import org.jeecg.modules.fw.entity.*;
import org.jeecg.modules.fw.service.IFwRoomCleanService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.fw.service.IFwRoomCleanUseConsumableService;
import org.jeecg.modules.fw.service.IFwRoomConsumableService;
import org.jeecg.modules.pos.entity.PosOrderGoodsPayment;
import org.jeecg.modules.rooms.Enum.RoomStatusEnum;
import org.jeecg.modules.rooms.entity.CesRoomLayout;
import org.jeecg.modules.rooms.entity.CesRooms;
import org.jeecg.modules.rooms.service.CesRoomLayoutServiceImpl;
import org.jeecg.modules.rooms.service.CesRoomsServiceImpl;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: fw_room_clean
 * @Author: jeecg-boot
 * @Date:   2023-04-17
 * @Version: V1.0
 */
@Api(tags="fw_room_clean")
@RestController
@RequestMapping("/fw/fwRoomClean")
@Slf4j
public class FwRoomCleanController extends JeecgController<FwRoomClean, IFwRoomCleanService> {
	@Autowired
	private IFwRoomCleanService fwRoomCleanService;
	 @Autowired
	 private CesRoomsServiceImpl cesRoomsService;
	 @Autowired
	 private IBusWaiterService busWaiterService;
	 @Resource
	 private CesRoomLayoutServiceImpl cesRoomLayoutService;
	 @Resource
	 private IFwRoomCleanUseConsumableService fwRoomCleanUseConsumableService;
	 @Resource
	 private IFwRoomConsumableService fwRoomConsumableService;
	/**
	 * 分页列表查询
	 *
	 * @param fwRoomClean
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "fw_room_clean-分页列表查询")
	@ApiOperation(value="fw_room_clean-分页列表查询", notes="fw_room_clean-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<FwRoomClean>> queryPageList(FwRoomClean fwRoomClean,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FwRoomClean> queryWrapper = QueryGenerator.initQueryWrapper(fwRoomClean, req.getParameterMap());
		Page<FwRoomClean> page = new Page<FwRoomClean>(pageNo, pageSize);
		IPage<FwRoomClean> pageList = fwRoomCleanService.page(page, queryWrapper);

		LambdaQueryWrapper<FwRoomConsumable> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(FwRoomConsumable::getHotelId, fwRoomClean.getHotelId());
		List<FwRoomConsumable> fwRoomConsumables = fwRoomConsumableService.list(lambdaQueryWrapper);

		pageList.getRecords().forEach(item -> {
			List<FwRoomCleanUseConsumable> list = new ArrayList<>();
			BusWaiter waiter = busWaiterService.getById(item.getWaiterId());
			if (waiter != null) {
				item.setWaiterName(waiter.getName());
			}
			CesRooms rooms = cesRoomsService.getById(item.getRoomId());
			if (rooms != null) {
				CesRoomLayout layout = cesRoomLayoutService.getById(rooms.getLayoutId());
				if (layout != null) {
					item.setLayoutName(layout.getName());
				}
			}
			LambdaQueryWrapper<FwRoomCleanUseConsumable> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
			lambdaQueryWrapper2.eq(FwRoomCleanUseConsumable::getRoomCleanId, item.getId());
			List<FwRoomCleanUseConsumable> useConsumableList = fwRoomCleanUseConsumableService.list(lambdaQueryWrapper2);
			fwRoomConsumables.forEach(u -> {
				FwRoomCleanUseConsumable fwRoomCleanUseConsumable = new FwRoomCleanUseConsumable();
				fwRoomCleanUseConsumable.setRoomConsumableId(u.getId());
				fwRoomCleanUseConsumable.setNum(0);
				fwRoomCleanUseConsumable.setRoomConsumable(u);
				Optional<FwRoomCleanUseConsumable> optional = useConsumableList.stream().filter(f -> f.getRoomConsumableId().equals(u.getId())).findFirst();
				if (optional.isPresent()) {
					fwRoomCleanUseConsumable.setNum(optional.get().getNum());
				}
				list.add(fwRoomCleanUseConsumable);
			});
			item.setUseConsumableList(list);
		});
		return Result.OK(pageList);
	}

	@GetMapping("/needCleanRoom")
	public List<FwRoomClean> needCleanRoom(FwRoomClean fwRoomClean, String hotelId){
		List<FwRoomClean> roomCleanList = fwRoomCleanService.needCleanRoom(hotelId);
//		List<FwRoomClean> roomCleanList = fwRoomCleanService.list(Wrappers.<FwRoomClean>lambdaQuery()
//				.eq(FwRoomClean::getState, 0).eq(FwRoomClean::getHotelId, hotelId));
		return roomCleanList;
	}

	/**
	 * 房间消耗品汇总统计
	 * @param startTime 开始日期
	 * @param endTime 截至日期
	 * @param hotelId
	 * @param type 1易耗品 2布草
	 * @return
	 */
	@ApiOperation(value = "房间消耗品汇总统计", notes = "房间消耗品汇总统计")
	@GetMapping(value = "/roomUseConsumableSummary")
	public Result<List<HashMap<String, Object>>> roomUseConsumableSummary(@RequestParam(name = "startTime") @JsonFormat(pattern = "yyyy-MM-dd")  @DateTimeFormat(pattern="yyyy-MM-dd") DateTime startTime,
																			  @RequestParam(name = "endTime") @JsonFormat(pattern = "yyyy-MM-dd")  @DateTimeFormat(pattern="yyyy-MM-dd") DateTime endTime,
																			  @RequestParam(name = "hotelId") String hotelId,@RequestParam(name = "type") Integer type) {
		List<HashMap<String, Object>> pageList = fwRoomCleanService.roomUseConsumableSummary(type, hotelId, startTime, endTime);
		return Result.OK(pageList);
	}

	/**
	 * 放扫记录汇总统计
	 * @param startTime 开始日期
	 * @param endTime 截至日期
	 * @param hotelId
	 * @return
	 */
	@ApiOperation(value = "放扫记录汇总统计", notes = "放扫记录汇总统计")
	@GetMapping(value = "/roomCleanSummary")
	public Result<List<HashMap<String, Object>>> roomCleanSummary(@RequestParam(name = "startTime") @JsonFormat(pattern = "yyyy-MM-dd")  @DateTimeFormat(pattern="yyyy-MM-dd") DateTime startTime,
																			 @RequestParam(name = "endTime") @JsonFormat(pattern = "yyyy-MM-dd")  @DateTimeFormat(pattern="yyyy-MM-dd") DateTime endTime,
																			 @RequestParam(name = "hotelId") String hotelId) {
		List<HashMap<String, Object>> pageList = fwRoomCleanService.roomCleanSummary( hotelId, startTime, endTime);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "fw_room_clean-添加")
	@ApiOperation(value="fw_room_clean-添加", notes="fw_room_clean-添加")
	//@RequiresPermissions("fw:fw_room_clean:add")
	@PostMapping(value = "/allotRoomClean")
	public Result<String> allotRoom(@RequestBody RoomCleanDto dto) {
		if (ObjectUtils.isEmpty(dto.getRoomCleanList())) {
			return Result.error("请先选择房间");
		}
		for (FwRoomClean fwRoomClean : dto.getRoomCleanList()) {
			CesRooms cesRooms = cesRoomsService.getById(fwRoomClean.getRoomId());
			if (ObjectUtils.isEmpty(cesRooms)) {
				return Result.error("房间不存在");
			}
			if (!cesRooms.getRoomStatus().equals(RoomStatusEnum.EMPTY_DIRTY.getKey()) && !cesRooms.getRoomStatus().equals(RoomStatusEnum.LIVE_DIRTY.getKey())) {
				return Result.error("房间不是脏房状态不可以置干净");
			}
			fwRoomClean.setHotelId(dto.getHotelId());
			fwRoomClean.setState(0);
			fwRoomClean.setTenantId(TokenUtils.currentTenantId());
			fwRoomClean.setRemark(dto.getRemark());
			fwRoomClean.setWaiterId(dto.getWaiterId());
		}
		fwRoomCleanService.saveBatch(dto.getRoomCleanList());
		return Result.OK("添加成功！");
	}

	/**
	 *   添加
	 *
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "fw_room_clean-添加")
	@ApiOperation(value="fw_room_clean-添加", notes="fw_room_clean-添加")
	//@RequiresPermissions("fw:fw_room_clean:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody RoomCleanDto dto) {
		if (ObjectUtils.isEmpty(dto.getRoomCleanList())) {
			return Result.error("请先选择房间");
		}
		for (FwRoomClean fwRoomClean : dto.getRoomCleanList()) {
			CesRooms cesRooms = cesRoomsService.getById(fwRoomClean.getRoomId());
			if (ObjectUtils.isEmpty(cesRooms)) {
				return Result.error("房间不存在");
			}
			if (!cesRooms.getRoomStatus().equals(RoomStatusEnum.EMPTY_DIRTY.getKey())
					&& !cesRooms.getRoomStatus().equals(RoomStatusEnum.LIVE_DIRTY.getKey())
					&& !cesRooms.getRoomStatus().equals(RoomStatusEnum.RESERVE.getKey())) {
				return Result.error("房间不是脏房状态不可以置干净");
			}
			fwRoomClean.setHotelId(dto.getHotelId());
			fwRoomClean.setTenantId(TokenUtils.currentTenantId());
			fwRoomClean.setRemark(dto.getRemark());
			fwRoomClean.setWaiterId(dto.getWaiterId());
		}
		Boolean res = fwRoomCleanService.saveBatch(dto.getRoomCleanList());
		if (res) {
			for (FwRoomClean fwRoomClean : dto.getRoomCleanList()) {
				CesRooms cesRooms = cesRoomsService.getById(fwRoomClean.getRoomId());
				if (ObjectUtils.isNotEmpty(cesRooms)) {
					if (cesRooms.getRoomStatus().equals(RoomStatusEnum.EMPTY_DIRTY.getKey())) {
						cesRooms.setLastRoomStatus(RoomStatusEnum.EMPTY_CLEAR.getKey());
						cesRooms.setRoomStatus(RoomStatusEnum.EMPTY_CLEAR.getKey());
					} else if (cesRooms.getRoomStatus().equals(RoomStatusEnum.LIVE_DIRTY.getKey())) {
						cesRooms.setLastRoomStatus(RoomStatusEnum.LIVE_CLEAR.getKey());
						cesRooms.setRoomStatus(RoomStatusEnum.LIVE_CLEAR.getKey());
					} else if (cesRooms.getRoomStatus().equals(RoomStatusEnum.RESERVE.getKey())){
						cesRooms.setLastRoomStatus(RoomStatusEnum.EMPTY_CLEAR.getKey());
					}
					cesRoomsService.updateById(cesRooms);
				}
			}
		}
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param fwRoomClean
	 * @return
	 */
	@AutoLog(value = "fw_room_clean-编辑")
	@ApiOperation(value="fw_room_clean-编辑", notes="fw_room_clean-编辑")
	//@RequiresPermissions("fw:fw_room_clean:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@Transactional(rollbackFor = Exception.class)
	public Result<String> edit(@RequestBody FwRoomClean fwRoomClean) {
		LambdaQueryWrapper<FwRoomCleanUseConsumable> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
		lambdaQueryWrapper2.eq(FwRoomCleanUseConsumable::getRoomCleanId, fwRoomClean.getId());
		fwRoomCleanUseConsumableService.remove(lambdaQueryWrapper2);
		List<FwRoomCleanUseConsumable> fwRoomCleanUseConsumables = new ArrayList<>();
		fwRoomClean.getUseConsumableList().forEach(t -> {
			if (t.getNum() > 0) {
				FwRoomCleanUseConsumable fwRoomCleanUseConsumable = new FwRoomCleanUseConsumable();
				fwRoomCleanUseConsumable.setHotelId(fwRoomClean.getHotelId());
				fwRoomCleanUseConsumable.setTenantId(fwRoomClean.getTenantId());
				fwRoomCleanUseConsumable.setRoomCleanId(fwRoomClean.getId());
				fwRoomCleanUseConsumable.setRoomConsumableId(t.getRoomConsumableId());
				fwRoomCleanUseConsumable.setNum(t.getNum());
				fwRoomCleanUseConsumables.add(fwRoomCleanUseConsumable);
			}
		});
		fwRoomCleanUseConsumableService.saveBatch(fwRoomCleanUseConsumables);
		fwRoomCleanService.updateById(fwRoomClean);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "fw_room_clean-通过id删除")
	@ApiOperation(value="fw_room_clean-通过id删除", notes="fw_room_clean-通过id删除")
	//@RequiresPermissions("fw:fw_room_clean:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		fwRoomCleanService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "fw_room_clean-批量删除")
	@ApiOperation(value="fw_room_clean-批量删除", notes="fw_room_clean-批量删除")
	//@RequiresPermissions("fw:fw_room_clean:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.fwRoomCleanService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "fw_room_clean-通过id查询")
	@ApiOperation(value="fw_room_clean-通过id查询", notes="fw_room_clean-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<FwRoomClean> queryById(@RequestParam(name="id",required=true) String id) {
		FwRoomClean fwRoomClean = fwRoomCleanService.getById(id);
		if(fwRoomClean==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(fwRoomClean);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param fwRoomClean
    */
    //@RequiresPermissions("fw:fw_room_clean:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FwRoomClean fwRoomClean) {
        return super.exportXls(request, fwRoomClean, FwRoomClean.class, "fw_room_clean");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("fw:fw_room_clean:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FwRoomClean.class);
    }

}
